const Router = require('koa-router')
const goods = new Router()
const db = require('../untils/database')

//商品详细信息
goods.post('/detailInfoById',async(ctx)=>{
    let goodsId = ctx.request.body.goodsId
    let sql = `SELECT * FROM product where id = '${goodsId}' `;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        
        ctx.body = {
            data: result[0],
            msg: 'success'
        }
    }else{
        ctx.body = {
            data: null,
            msg: 'successs'
        }
    }
})
//根据大类查商品
goods.post('/getGoodsInfoByCategoryID',async(ctx)=>{
    let categoryId = ctx.request.body.categoryId //小类别
    let pageSize =  5 //每页显示数量
    let start = ctx.request.body.pageNum ? ((ctx.request.body.pageNum-1)*pageSize) : 0
    let sql = `SELECT id,productImg,productName,oldPrice,presentPrice FROM product WHERE mainId = '${categoryId}' limit ${start},${pageSize}`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            message: result,
            msg: 'success'
        }
    }else{
        ctx.body = {
            message: null,
            msg: 'successs'
        }
    }
})

//根据搜索条件模糊查询商品
goods.post('/getGoodsListBySearch',async(ctx)=>{
    let searchContent = ctx.request.body.searchContent //搜索内容
    let pageSize =  5 //每页显示数量
    let start = ctx.request.body.pageNum ? ((ctx.request.body.pageNum-1)*pageSize) : 0
    let sql = `SELECT * from product WHERE productName LIKE '%${searchContent}%' limit ${start},${pageSize}`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            message: result,
            msg: 'success'
        }
    }else{
        ctx.body = {
            message: null,
            msg: 'successs'
        }
    }
})

//加购物车
goods.post('/addGoodsToCart',async(ctx)=>{
    let userId = ctx.request.body.userId
    let goodsId = ctx.request.body.goodsId
    let goodsName = ctx.request.body.goodsName
    let goodsImg = ctx.request.body.goodsImg
    let goodsPrice = ctx.request.body.goodsPrice
    let goodsQuanity = ctx.request.body.goodsQuanity
    let sql = `SELECT * FROM shopping_cart WHERE goodsId='${goodsId}' and userId = '${userId}' `;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        let quanity = result[0].quanity
        // ctx.body = {
        //     message: quanity,
        //     msg: 'success'
        // }
        let sql = `UPDATE shopping_cart SET quanity = '${quanity+1}'  WHERE goodsId='${goodsId}'`; 
        let result1 = await new Promise((resolve,reject)=>{
            return db.query(sql,(err,data)=>{
                if(err) throw err;
                let obj = {
                    msg: 'success',
                }
                resolve(obj)
            })   
        })
        if(result1){
            ctx.body = result1
        }
    }else{
        let sql =`INSERT INTO shopping_cart (userId, goodsId,name, img, price, quanity) values ('${userId}','${goodsId}','${goodsName}', '${goodsImg}', '${goodsPrice}', '${goodsQuanity}')`
        let result1 = await new Promise((resolve,reject)=>{
            return db.query(sql,(err,data)=>{
                if(err) throw err;
                if(data.length>0){
                    resolve(data)
                }else{
                    resolve(false)
                }
            })   
        })
        if(result1){
            ctx.body = {
                message: result1,
                msg: 'success'
            }
        }else{
            ctx.body = {
                message: null,
                msg: 'successs'
            }
        }
    }
    
})

//购物车商品分页查询
goods.post('/cartGoodsInfo',async(ctx)=>{
    let userId = ctx.request.body.userId
    let pageSize =  3 //每页显示数量
    let start = ctx.request.body.pageNum ? ((ctx.request.body.pageNum-1)*pageSize) : 0
    let sql = `SELECT * FROM shopping_cart WHERE userId='${userId}' limit ${start},${pageSize} `;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            message: result,
            msg: 'success'
        }
    }else{
        ctx.body = {
            message: null,
            msg: 'successs'
        }
    }
})

//商品推荐
goods.get('/GoodRecomendList',async(ctx)=>{
    let sql = `SELECT id,productImg,productName,oldPrice,presentPrice FROM product WHERE isRecommend = '1' `;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            message: result,
            msg: 'success'
        }
    }else{
        ctx.body = {
            message: null,
            msg: 'successs'
        }
    }
})
//删除购物车商品
goods.delete('/deleteCartGoods',async(ctx)=>{
    let Id = ctx.request.body.Id 
    // console.log(Id.split(','));
    let sql = `DELETE FROM shopping_cart WHERE id in (${Id})`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            state: 200,
            msg: "删除购物车成功",
            data: result,
        }
    }
})
//改变购物车商品数量
goods.post('/changCartGoodsQuanity',async(ctx)=>{
    let Id = ctx.request.body.Id 
    let quanity = ctx.request.body.quanity
    if(quanity){
        let sql = `UPDATE shopping_cart SET quanity = '${quanity}' WHERE id='${Id}'`
        let result =  await new Promise((resolve,reject)=>{
            return db.query(sql,(err,data)=>{
                if(err) throw err;
                if(data){
                    resolve(data)
                }else{
                    resolve(false)
                }
            })   
        })
        if(result){
            ctx.body = {
                state: 200,
                msg: "success",
                data: result,
            }
        }else{
            ctx.body = {
                msg: "系统开小差"
            }
        }
    }
    
})
//查询商品库存
goods.post('/goodsStockQuery',async(ctx)=>{
    let goodsId = ctx.request.body.goodsId 
    let stock = {}
    let res = {}
    for(let item of goodsId){
        let sql = `SELECT productName,stock FROM product WHERE id = '${item}'`
        let result = await new Promise((resolve,reject)=>{
            return db.query(sql,(err,data)=>{
                if(err) throw err;
                if(data){
                    resolve(data)
                }else{
                    resolve(false)
                }
            })   
        })
        let key = result[0].productName
        stock[key] = result[0].stock
        
        // console.log("=======result======",result1[0].stock);
    }
    // stock.push(res)
    // console.log("=======stock======",stock);
    ctx.body = {
        state: 200,
        msg: "success",
        data: stock,
    }
})
//商品结算
goods.post('/settleGoods',async(ctx)=>{
    let Id = ctx.request.body.Id 
    let quanity = ctx.request.body.quanity
    let goodsId = ctx.request.body.goodsId
    console.log(Id,quanity,goodsId);
    // if(result){
    let stock = []
    for(let item of goodsId){
        let sql1 = `SELECT stock FROM product WHERE id = '${item}'`
        let result1 = await new Promise((resolve,reject)=>{
            return db.query(sql1,(err,data)=>{
                if(err) throw err;
                if(data){
                    resolve(data)
                }else{
                    resolve(false)
                }
            })   
        })
        stock.push(result1[0].stock)
        // console.log("=======result======",result1[0].stock);
    }
    console.log("=======stock======",stock);
    let isStock = true
    for (let index = 0; index < stock.length; index++) {
        if(stock[index]<quanity[index]){
            isStock = false
            break
        }else{
            stock[index] -= quanity[index]
        }
    }
    console.log("=======stock======",stock);
    if(isStock){
        if(Id){
            let sql = `DELETE FROM shopping_cart WHERE id in (${Id})`;
            let result = await new Promise((resolve,reject)=>{
                return db.query(sql,(err,data)=>{
                    if(err) throw err;
                    if(data){
                        resolve(data)
                    }else{
                        resolve(false)
                    }
                })   
            })
        }
        for(let i = 0; i<stock.length; i++){
            let sql2 = `UPDATE product SET stock = '${stock[i]}' WHERE id='${goodsId[i]}'`
            await new Promise((resolve,reject)=>{
                return db.query(sql2,(err,data)=>{
                    if(err) throw err;
                    if(data){
                        resolve(data)
                    }else{
                        resolve(false)
                    }
                })   
            })
        }
        ctx.body = {
            state: 200,
            msg: "结算成功",
            // data: result,
        }
    }else{
        ctx.body = {
            state: 500,
            msg: "存在库存不足商品",
            // data: result,
        }
    } 
    
        
    // }
})
module.exports = goods;